package com.ksyzt.ksite2.client.orgnization;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.ksyzt.gwt.client.event.HasMessageHandlers;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.gwt.client.event.MessageHandler;
import com.ksyzt.ksite2.shared.OrgType;
import com.ksyzt.ksite2.shared.modle.ORGANIZATIONObj;

public class DlgOrgnizationSelection extends DialogBox implements
		HasMessageHandlers {

	private static DlgOrgnizationSelectionUiBinder uiBinder = GWT
			.create(DlgOrgnizationSelectionUiBinder.class);

	interface DlgOrgnizationSelectionUiBinder extends
			UiBinder<Widget, DlgOrgnizationSelection> {
	}

	ORGANIZATIONObj m_org;
	private MessageHandler m_tree_click = new MessageHandler() {

		public void onMessage(Object sender, Integer message, Object value) {
			TreeItem it = (TreeItem) value;
			ORGANIZATIONObj org = (ORGANIZATIONObj) it.getUserObject();
			m_org = org;
			updateState();
		}
	};

	public DlgOrgnizationSelection() {
		setWidget(uiBinder.createAndBindUi(this));
		setHTML("<b>选择分类</b>");
		tree.setPixelSize(250, 300);
		tree.addMessageHandler(m_tree_click);
		tree.EnableCreate(false);
		updateState();

	}

	protected void updateState() {
		if (m_org == null) {
			btnOK.setEnabled(false);
		} else {
			btnOK.setEnabled(true);
		}

	}

	@UiField
	Button btnOK;
	@UiField
	Button btnCancel;
	@UiField
	OrgnizationTree tree;

	public HandlerRegistration addMessageHandler(MessageHandler handler) {

		return addHandler(handler, MessageEvent.TYPE);
	}

	@UiHandler("btnOK")
	void onOK(ClickEvent e) {
		MessageEvent ev = new MessageEvent(MessageEvent.OK, m_org);
		fireEvent(ev);
	}

	@UiHandler("btnCancel")
	void onCancel(ClickEvent e) {
		MessageEvent ev = new MessageEvent(MessageEvent.CANCEL, m_org);
		fireEvent(ev);
	}

	public void init(int userid, int orgtype) {
		GWT.log(userid + " " + orgtype);
		tree.initTree(userid, orgtype, OrgType.getOrgNameByType(orgtype), true);
	}

}
